package com.semanticweb.webapp.model.ontology;

import org.apache.lucene.document.Document;

import com.semanticweb.webapp.ontology.CIDOC;
import com.semanticweb.webapp.ontology.Ont;
import com.semanticweb.webapp.ontology.Query;
import com.semanticweb.webapp.search.IDocument;
import com.semanticweb.webapp.search.SearchMD;

/**
 * Class which represents 'Zbirka' from the chart.
 * 
 * @author Lab
 * 
 */
public class Collection extends DefaultAbstractEntity<String> implements IDocument {

    public static final String ONT_PART_ADDITION = "pa";
    public static final String ONT_COLLECTION = "collection";

    public Collection(final String id) {
        super(id);
    }

    @Override
    public void toRDF() {
        if (this.value == null) {
            return;
        }

        final Query query = new Query();
        final String[] result = query.select("collection").type("collection", CIDOC.E78.queryValue())
                .label("collection", this.value).type("partAddition", CIDOC.E79.queryValue())
                .connect("partAddition", CIDOC.P110.queryValue(), "collection").find();

        final String itemURI = Item.formatItemURI(this.id);
        String partAdditionURI;
        if (result == null || result.length == 0) {
            partAdditionURI = Ont.formatURI(this.id, ONT_PART_ADDITION);
            final String collectionURI = Ont.formatURI(this.id, ONT_COLLECTION);

            Ont.getOntology().createIndividual(CIDOC.E79.getFullValue(), partAdditionURI);
            Ont.getOntology().createIndividual(CIDOC.E78.getFullValue(), collectionURI);
            Ont.getOntology().addLabel(collectionURI, this.value);

            Ont.getOntology().connectIndividuals(partAdditionURI, CIDOC.P110.getFullValue(), collectionURI);
        } else {
            partAdditionURI = result[0];
        }

        // connect to item
        Ont.getOntology().connectIndividuals(partAdditionURI, CIDOC.P111.getFullValue(), itemURI);
    }

    public void fromRDF() {
        final String itemQueryURI = Item.formatItemQueryURI(this.id);
        final Query q = new Query();
        final String[] result = q.selectLabel().type("partAddition", CIDOC.E79.queryValue())
                .connect("partAddition", CIDOC.P111.queryValue(), itemQueryURI)
                .type("collection", CIDOC.E78.queryValue())
                .connect("partAddition", CIDOC.P110.queryValue(), "collection").findLabel("collection");
        if (result != null && result.length > 0) {
            this.value = result[0];
        }
    }

    @Override
    public void toIndexDocument(final Document doc) {
        if (this.value != null) {
            doc.add(SearchMD.COLLECTION.createField(this.value));
            doc.add(SearchMD.CONTENT.createField(this.value));
        }
    }

}
